<script setup>
import Header from "@/components/header/Header.vue";
import CodeLogin from "@/views/login/components/CodeLogin.vue";
import PasswordLogin from "@/views/login/components/passwordLogin.vue";
import Agreement from "@/views/login/components/Agreement.vue";
import {ref, markRaw, computed, reactive} from "vue";
import {useRouter, useRoute} from "vue-router";
import api from "@/api/index.js";
import {showToast, closeToast} from "vant";

const router = useRouter();
const route = useRoute();

router.beforeRouteEnter = (to, from) => {
  console.log("to------------", to);
  console.log("from----------", from);
  // 在渲染该组件的对应路由被验证前调用
  // 不能获取组件实例 `this` ！
  // 因为当守卫执行时，组件实例还没被创建！
};

const loginType = ref("codeLogin");
const loginTypeComponent = ref(markRaw(CodeLogin));
const changeLoginType = (type) => {
  loginType.value = type;
  console.log("loginType.value", loginType.value);
  if (type === "codeLogin") {
    loginTypeComponent.value = markRaw(CodeLogin);
  } else {
    loginTypeComponent.value = markRaw(PasswordLogin);
  }
};

const agree = ref(false);
const setAgreementAgree = (e) => {
  agree.value = e;
};

let codeLoginData = reactive({
  username: "",
  code: "",
});
const emitCodeLogin = (e) => {
  codeLoginData.username = e?.username;
  codeLoginData.code = e?.code;
};
let passwordLoginData = reactive({
  username: "",
  password: "",
});
const emitPasswordLogin = (e) => {
  passwordLoginData.username = e?.username;
  passwordLoginData.password = e?.password;
};

const buttonState = computed(() => {
  if (agree.value) {
    if (loginType.value === "codeLogin") {
      return codeLoginData?.username && codeLoginData?.code;
    }
    return passwordLoginData?.username && passwordLoginData?.password;
  }
  return false;
});

const loginButtonLoading = ref(false);
const deleteCode = ref(0);
const loginClick = () => {
  if (loginButtonLoading.value) {
    return;
  }
  if (buttonState.value) {
    if (loginType.value === "codeLogin") {
      loginButtonLoading.value = true;
      let formdata = new FormData();
      formdata.append("username", codeLoginData?.username);
      formdata.append("userType", "member");
      formdata.append("phoneValidCode", codeLoginData?.code);
      formdata.append("loginType", "smsCode");
      api
          .codeLogin(formdata)
          .then((res) => {

            // showToast('登录成功')
            localStorage.setItem("tokenData", JSON.stringify(res.data));
            // setTimeout(() => {
            // router.push("/").then(() => {
            //   closeToast();
            // });
            api.getTmpToken().then(res => {
              const shortToken = res.data


            });
            api.getUserinfo().then(info => {
              console.log('userinfo', info)
              if (info?.code === '200') {
                api.afterLogin({
                  id: info?.data?.memberId,
                  name: info?.data?.memberName,
                  telephone: info?.data?.telephone,
                  nickName: info?.data?.nickName,
                }).then(res2 => {
                  if (res2?.code === '200') {
                    api.pointsRegister(
                        {
                          uid: info?.data?.memberId

                        }
                    )
                  }
                })


              }

            })
            let prePath = localStorage.getItem('prevFullPath')
            if (prePath === '/settinginterface') {
              prePath = '/'
            }
            router.push(prePath).then(() => {
              closeToast();
            });
            // }, 1500);
          })
          .catch(() => {
            codeLoginData.code = "";
            deleteCode.value += 1;
          })
          .finally(() => {
            loginButtonLoading.value = false;
          });
    }
  }
};
</script>

<template>
  <div class="login">
    <Header title="登录" :back="true" path="/"/>
    <div class="login_content">
      <div class="tab_list">
        <div
            class="tab"
            :class="{ active_tab: loginType === 'codeLogin' }"
            @click="changeLoginType('codeLogin')"
        >
          验证码登录
          <div class="line" v-if="loginType === 'codeLogin'"/>
        </div>
        <!--        <div class="tab" :class="{'active_tab': loginType === 'passWordLogin'}" @click="changeLoginType('passWordLogin')">-->
        <!--          密码登录-->
        <!--          <div class="line" v-if="loginType === 'passWordLogin'" />-->
        <!--        </div>-->
      </div>
      <keep-alive>
        <component
            :is="loginTypeComponent"
            :deleteCode="deleteCode"
            @emitCodeLogin="emitCodeLogin"
            @emitPasswordLogin="emitPasswordLogin"
        />
      </keep-alive>
      <div class="agreement_box">
        <Agreement @setAgreementAgree="setAgreementAgree" :agree="agree"/>
      </div>
      <div
          class="button"
          @click="loginClick"
          :class="{ primary_button: buttonState && !loginButtonLoading }"
      >
        <van-loading v-if="loginButtonLoading" type="spinner" color="#4FAC91"/>
        <span v-else>登录/注册</span>
      </div>
      <!--      <div class="register">注册账号</div>-->
      <div class="bg">
        <img src="@/assets/images/index/mine_bg.png" alt=""/>
        <div class="bg_none"></div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .login_content {
    position: relative;
    flex: 1;

    .tab_list {
      z-index: 1;
      display: flex;
      padding-top: 8rem;
      margin-left: 3rem;

      .tab {
        font-size: 1.4rem;
        color: #999999;
        margin-right: 2rem;
      }

      .active_tab {
        font-size: 1.8rem;
        color: #333333;
        font-weight: bold;
      }

      .line {
        margin-top: -0.2rem;
        width: 3.1rem;
        height: 0.5rem;
        background: linear-gradient(90deg, #43d19d 0%, #fbeaa8 92%);
        border-radius: 0.4rem;
      }
    }

    .agreement_box {
      margin-top: 5rem;
      padding: 0 3rem;
    }

    .button {
      margin: 2rem 3rem;
      height: 5rem;
      line-height: 5rem;
      font-size: 16px;
      border-radius: 0.5rem;
      text-align: center;
      background: rgb(203, 231, 220);
      color: #ffffff;
    }

    .primary_button {
      background: var(--van-primary-color);
      color: #ffffff;
    }

    .primary_button:active {
      background: #4b947f;
    }

    .register {
      font-size: 1.6rem;
      color: var(--van-primary-color);
      text-align: center;
      margin-top: 2rem;
    }

    .bg {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      display: flex;
      flex-direction: column;
      z-index: -1;

      img {
        width: 100vw;
      }

      .bg_none {
        flex: 1;
        background-color: #fffffc;
      }
    }
  }
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
